package com.hefei.blog.web.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.hefei.blog.base.data.Data;
import com.hefei.blog.base.lang.Global;
import com.hefei.blog.web.common.utils.AntPathMatcher;
import com.hefei.blog.web.common.utils.LoginInclude;
import com.hefei.common.util.StringUtils;
import com.hefei.frontend.framework.base.CookieConstants;
import com.hefei.frontend.framework.base.FrontendConstants;
import com.hefei.frontend.framework.base.UserCookieUtil;
import com.hefei.frontend.framework.base.user.UserCookie;
import com.hefei.frontend.framework.http.request.CommonParameter;
import com.hefei.frontend.framework.http.request.CommonParameterThreadLocal;
import com.hefei.frontend.framework.http.request.RequestThreadLocal;

public class LoginIncludeFilter implements Filter{
	
	private static Logger logger =  Logger.getLogger(LoginIncludeFilter.class);

	AntPathMatcher m = new AntPathMatcher();
	
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)arg0;
		HttpServletResponse response = (HttpServletResponse)arg1;
		try{
			String context = request.getContextPath();
			
			request.setAttribute("base", context);
			request.setAttribute("statici", Global.STATIC_DOMAIN_I);
			
			request.setAttribute("staticpic", Global.STATIC_DOMAIN_PIC);
			request.setAttribute("statichtml", Global.STATIC_DOMAIN_HTML);
			request.setAttribute("staticfile", Global.STATIC_DOMAIN_FILE);
			
			String url = request.getRequestURI();
			url = url.substring(context.length());
			
			UserCookie userCookie = UserCookieUtil.getUserCookie(request, CookieConstants.COOKIE_NAME_WEB);
			if(userCookie != null){
				CommonParameter commonParameter = new CommonParameter();
				commonParameter.setUserCookie(userCookie);
				request.setAttribute("profile", userCookie);
				
				CommonParameterThreadLocal.set(commonParameter);
			}
			
			if(!LoginInclude.matchIncludes(url)){
				chain.doFilter(request, response);
			}else{
				Long userId = CommonParameterThreadLocal.getUserId();
				logger.info(RequestThreadLocal.getTimer() + " userId:"+userId);
				if(userId == null){
					
					if (isAjaxRequest((HttpServletRequest) request)) {
			        	response.setContentType("application/json;charset=UTF-8");
						Gson gson = new Gson();
						response.getWriter().print(gson.toJson(Data.failure("您还没有登录!")));
			        }else {
						String param = request.getQueryString();
						if(StringUtils.isNotBlank(param)){
							url = url + "?" + param;
						}
						url = java.net.URLEncoder.encode(url, "UTF-8");
						response.sendRedirect(FrontendConstants.LOGIN_URL + "?backurl=" + url);
			        }
				}else{
					chain.doFilter(request, response);
				}
			}
		} catch (Exception e) {
			logger.error(RequestThreadLocal.getTimer() + " error", e);
		}finally{
			CommonParameterThreadLocal.clean();
		}
	}

	public void destroy() {
	}
	/**
	 * 判断是否为Ajax请求 <功能详细描述>
	 * 
	 * @param request
	 * @return 是true, 否false
	 * @see [类、类#方法、类#成员]
	 */
	public static boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equals(header))
			return true;
		else
			return false;
	}
	public void init(FilterConfig filterConfig) throws ServletException {
		try{
			LoginInclude.init();
		}catch(Exception e){
			logger.error(" error", e);
			System.exit(0);
		}
	}
}